package od.igor.petrov.servlet;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import od.igor.petrov.utils.TestTableBeanPreparedCollection;

public class RequestData extends HttpServlet {

	private static final long serialVersionUID = -6514742502146709994L;

	public void doGet(HttpServletRequest request, HttpServletResponse response){
		sortBy = parseSort(request.getParameter("sortby"));
		orderDesc = parseOrder(request.getParameter("orderbydesc"));
		TestTableBeanPreparedCollection.setSortBy(sortBy);
		TestTableBeanPreparedCollection.setOrder(orderDesc);
		currentSession = request.getSession();
		currentSession.setAttribute("orderDesc", !orderDesc);
		try {
			response.sendRedirect(REDIRECT_TO);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	/* ========================================== *
	 *          PARSING REQUEST DATA
	 * ========================================== */
	
	private int parseSort(String sorting){
		int x = 1;
		try {
			x = Integer.parseInt(sorting); 
		} catch (NumberFormatException e) {
			return 1;
		}
		return x;
	}
	
	private boolean parseOrder(String ordering){
		return Boolean.parseBoolean(ordering);
	}

	private int sortBy = 1;
	private boolean orderDesc = false;
	private HttpSession currentSession = null;
	private static final String REDIRECT_TO = "../Table.jsp";
}
